package web.controller.common;

import common.consts.CaptchaUsage;
import common.consts.ContentType;
import common.validation.ValidationResult;
import domain.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.AccountService;
import service.CaptchaService;
import service.ServiceResponse;
import web.Routes;
import web.controller.Base;
import web.req.RegisterRequest;

/**
 * Created by aceyin on 2015/6/8 0008.
 */
@RestController
@RequestMapping(Routes.Common.REGISTER)
public class Register extends Base {
    private static Logger LOGGER = LoggerFactory.getLogger(Register.class);
    @Autowired
    private AccountService accountService;
    @Autowired
    private CaptchaService captchaService;

    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse register(@RequestBody RegisterRequest request) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Receiving request: " + request);
        }
        ValidationResult result = request.validate();
        if (result.isFailed()) {
            return fail(result.getMessage());
        }

        ServiceResponse serviceResponse = captchaService.validate(request.getUsername(), CaptchaUsage.REGISTER.name(), request.getToken(), request.getCaptcha());

        if (serviceResponse.isFailed()) {
            return serviceResponse;
        }

        Account account = new Account();
        account.setUsername(request.getUsername());
        account.setPassword(request.getPassword());
        account.setType(request.getType());

        serviceResponse = accountService.register(account);
        return serviceResponse;
    }
}
